import com.genexususa.eo.google.connection.CustomerSyncManager;
import com.genexususa.eo.google.connection.ReportManager;
import com.genexususa.eo.google.connection.SyncManager;
import com.genexususa.eo.google.data.ErrorsStruct;
import com.genexususa.eo.google.data.GA_Report;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import java.io.*;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

public class runSync {

    private final static String error = "<HasError>true</HasError>";

    public static void main(String[] args){
        if (args.length != 5){
            System.err.println("Arguments must be 5:");
            System.err.println("\tfirst the name of the clients file");
            System.err.println("\tsecond the location of the downloaded reports");
            System.err.println("\tthird the time between requests");
            System.err.println("\tfourth the amount of retries for each client");
            System.err.println("\tfifth the location of the getClients script");
        }else{

            try
            {

                Process proc = Runtime.getRuntime().exec("/bin/sh " + args[4] + " " + args[0]);

                System.out.println("/bin/sh " + args[4] + " " + args[0]);
                proc.waitFor();


                Long start = System.currentTimeMillis();

                ArrayList<String> allClients = new ArrayList<String>();

                ArrayList<String> records = new ArrayList<String>();
                BufferedReader reader = new BufferedReader(new FileReader(args[0]));
                String line;
                while ((line = reader.readLine()) != null) {
                    records.add(line);
                    String[] splitClients = line.split(";");
                    for (String splittedClient : splitClients){
                        if (allClients.contains(splittedClient)) {
                            System.out.println("Repeated Client: " + splittedClient);
                        }else {
                            allClients.add(splittedClient);
                        }
                    }

                }
                reader.close();


                CustomerSyncManager customerSyncManager = new CustomerSyncManager();


                //System.out.println(allClients);



                for (String l : records) {
                    org.joda.time.DateTime dateAux =  new org.joda.time.DateTime();

                    System.out.println("Calling GetTotalReportForClients for clients:");
                    System.out.println(l);
                    System.out.println("at time: " + dateAux.toString(ISODateTimeFormat.dateHourMinute()));

                    customerSyncManager.GetCustomersChangedData(l, args[1], Long.parseLong(args[2]), Integer.parseInt(args[3]));
                }




                Long end = System.currentTimeMillis();

                System.out.println(String.format("%d min, %d sec",
                        TimeUnit.MILLISECONDS.toMinutes(end - start),
                        TimeUnit.MILLISECONDS.toSeconds(end - start) -
                                TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(end - start))
                ));

                /*String remaining = remainingClients(allClients, args[1]);

                String errorLocation = args[1] + File.separator + "clientsError.txt";

                FileWriter fw = new FileWriter(errorLocation);
                BufferedWriter bw = new BufferedWriter(fw);

                bw.write(remaining);
                bw.flush();
                bw.close();*/

                /*org.joda.time.DateTime date =  new org.joda.time.DateTime();

                System.out.println("Calling synchronizeadwordsaccounts.sh at " + date.toString(ISODateTimeFormat.dateHourMinute()));

                Process p = Runtime.getRuntime().exec("/bin/sh ./synchronizeadwordsaccounts.sh " + args[1]);

                StringBuilder sb = new StringBuilder();
                InputStream is = p.getInputStream();

                int c;
                while ((c = is.read()) != -1) {
                    sb.append((char) c);
                }

                System.out.println(sb.toString());*/


            }
            catch (Exception e)
            {
                System.err.format("Exception occurred trying to read '%s'.", args[0]);
                e.printStackTrace();
            }


        }


    }

    private static String remainingClients(ArrayList<String> clients, String location){

        File folder = new File(location);
        File[] listOfFiles = folder.listFiles();

        for (int i = 0; i < listOfFiles.length; i++) {
            if (listOfFiles[i].isFile()) {
                String filename = listOfFiles[i].getName();
                String[] splitted = filename.split("\\.");
                if (splitted[1].equalsIgnoreCase("xml")){

                    if (clients.contains(splitted[0])){
                        clients.remove(splitted[0]);
                    }
                }
            }
        }
        String result = "";

        for (String client : clients){
            //System.out.println("Missing: " + client);

            result += client + ";";
        }

        if (!result.equalsIgnoreCase(""))
            return result.substring(0, result.length() - 1);
        return result;


    }


    private static String readFile(String fileName) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(fileName));
        try {
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();

            while (line != null) {
                sb.append(line);
                sb.append("\n");
                line = br.readLine();
            }
            return sb.toString();
        } finally {
            br.close();
        }
    }
}
